<template>
  <div>
    <el-drawer
      :title="order_data.name + '外贸订单产品'"
      :visible.sync="childFormVisible"
      :wrapper-closable="false"
      append-to-body
      size="60%"
      class="mt-dialog"
      @close="hide"
    >
      <div style="margin: 20px;">
        <el-form :model="temp" :rules="rules" label-position="right" label-width="140px">
          <!-- 最常用的三个参数 -->
          <el-row :gutter="24">
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <el-form-item label="中文名称" prop="cnname">
                <el-input v-model="temp.cnname" placeholder="请输入中文产品名称" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <el-form-item label="英文名称" prop="enname">
                <el-input v-model="temp.enname" placeholder="请输入英文产品名称" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="细节要求" prop="parameters">
                <el-input v-model="temp.parameters" type="textarea" :rows="3" placeholder="请输入产品技术参数" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="备注信息" prop="note">
                <el-input v-model="temp.note" type="textarea" :rows="3" placeholder="请输入产品备注信息" />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 其他产品信息 -->
          <el-row :gutter="24">
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <el-form-item label="SKU编号" prop="sku">
                <el-input v-model="temp.sku" placeholder="请输入SKU编号" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <el-form-item label="产品型号" prop="model">
                <el-input v-model="temp.model" placeholder="请输入产品型号" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <el-form-item label="产品类型" prop="product_type">
                <el-select v-model="temp.product_type" placeholder="请选择产品类型" style="width: 100%">
                  <el-option label="样品图" value="样品图" />
                  <el-option label="主产品" value="主产品" />
                  <el-option label="配件" value="配件" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <el-form-item label="数量" prop="quantity">
                <el-input v-model.number="temp.quantity" type="number" placeholder="请输入数量" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <el-form-item label="PI交货周期(天)" prop="pi_lead_period">
                <el-input v-model.number="temp.pi_lead_period" type="number" placeholder="请输入天数" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <el-form-item label="厂家供货周期(天)" prop="manufacture_lead_period">
                <el-input v-model.number="temp.manufacture_lead_period" type="number" placeholder="请输入天数" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row v-if="this.$store.getters.roles.indexOf('source_manager') !== -1">
            <el-col :span="24">
              <el-form-item label="供应商信息">
                <el-input v-model="temp.supplier_note" type="textarea" :rows="2" placeholder="请输入供应商信息" />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 文件上传 - 独占一行 -->
          <el-row>
            <el-col :span="24">
              <el-form-item label="产品文件" prop="crmfiles">
                <div v-if="temp.crmfiles && temp.crmfiles.length > 0" class="file-list-display">
                  <div v-for="(item, index) in temp.crmfiles" :key="index" class="file-item">
                    <el-image
                      v-if="item.content_type.indexOf('image') !== -1"
                      :src="item.url"
                      :preview-src-list="[item.url]"
                      class="file-icon"
                    />
                    <svg-icon
                      v-else-if="item.filename.indexOf('pdf') !== -1"
                      icon-class="pdf"
                      class="file-icon"
                    />
                    <svg-icon
                      v-else-if="item.filename.indexOf('xlsx') !== -1"
                      icon-class="xlsx"
                      class="file-icon"
                    />
                    <svg-icon
                      v-else-if="item.filename.indexOf('xls') !== -1"
                      icon-class="xls"
                      class="file-icon"
                    />
                    <svg-icon
                      v-else-if="item.filename.indexOf('zip') !== -1"
                      icon-class="zip"
                      class="file-icon"
                    />
                    <svg-icon
                      v-else
                      icon-class="document"
                      class="file-icon"
                    />
                    <div class="file-name">{{ item.filename }}</div>
                  </div>
                </div>
                <crmfilequickuploader :default-expanded="true" @insert="handleInsertFile" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-row type="flex" justify="center">
          <el-button @click="childFormVisible = false;editloading=false;">取 消</el-button>
          <el-button type="primary" :loading="editloading" @click="confirm">确 定</el-button>
        </el-row>
      </div>
    </el-drawer>
    <el-row style="justify-content: left;display: flex; ">
      <el-button size="mini" type="primary" icon="el-icon-plus" round @click="handleShowEdit">添加产品
      </el-button>
      <crmdownloador
        :table-name="table_name"
        :fields="downloadTemp.fields"
        :filters="downloadTemp.filters"
        :available-fields="availableFields"
      />
    </el-row>
    <el-table
      v-loading="listLoading"
      :data="data"
      border
      fit
      highlight-current-row
      :default-sort="{prop: 'create_at', order: 'descending'}"
      style="width: 100%"
    >
      <el-table-column align="center" label="文件" prop="crmfiles" width="150">
        <template slot-scope="scope">
          <div class="file-list">
            <div v-for="(item, index) in scope.row.crmfiles" :key="index" class="file-item-table">
              <!-- 图片直接显示缩略图 -->
              <el-image
                v-if="item.content_type && item.content_type.indexOf('image') !== -1"
                :src="item.url"
                :preview-src-list="[item.url]"
                class="file-thumbnail"
                fit="cover"
              >
                <div slot="error" class="image-error">
                  <i class="el-icon-picture-outline" />
                </div>
              </el-image>
              <!-- 其他文件显示对应图标 -->
              <a v-else :href="item.url" target="_blank" :title="'点击下载: ' + item.filename" class="file-icon-link" @click.prevent="downloadFile(item)">
                <svg-icon
                  :icon-class="getFileIcon(item)"
                  class="file-type-icon"
                />
                <div class="file-name-small">{{ getFileExtension(item.filename) }}</div>
              </a>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column align="center" label="技术参数" prop="parameters" width="250" />
      <el-table-column align="center" label="备注" prop="note" width="250" />
      <el-table-column
        v-if="this.$store.getters.roles.indexOf('source_manager') !== -1"
        align="center"
        label="供应商信息"
        prop="supplier_note"
        width="250"
      />
      <el-table-column align="center" label="名称" prop="cnname" width="200">
        <template slot-scope="scope">
          <h3>{{ scope.row.enname }}</h3>
          <span style="display: block">中文名称:{{ scope.row.cnname }}</span>
          <span style="display: block">产品编码：{{ scope.row.sku }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="产品类型" prop="product_type" width="120" />
      <el-table-column align="center" label="数量" prop="quantity" width="100" />

      <el-table-column align="center" label="产品型号" prop="model" width="120" />

      <el-table-column align="center" label="PI交货周期(天)" prop="pi_lead_period" width="150" />

      <el-table-column align="center" label="厂家供货周期(天)" prop="manufacture_lead_period" width="150" />

      <el-table-column align="center" label="创建时间" prop="create_at" width="180" />

      <el-table-column align="center" label="操作" fixed="right" width="100">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEditFromTable(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="handleDeleteFromTable(scope.row)">删除</el-button>
        </template>
      </el-table-column>
      <el-pagination
        v-if="data.length"
        background
        class="mt-pagination"
        :current-page="page"
        :page-sizes="[10,20,50,100]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @current-change="handlePageChange"
      />
    </el-table>
  </div>
</template>

<script>
import { Get, Post, Put, Delete, QueryProduct } from '@/api/crm/crmproduct'
import qs from 'qs'
import Crmfilequickuploader from '../../../components/crmfilequickuploader'
import Crmdownloador from '../../../components/crmdownloador'
const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Crmorderproduct',
  components: { Crmdownloador, Crmfilequickuploader },
  props: ['order_data'],
  data() {
    return {
      downloadTemp: {
        table_name: 'CRMProduct', // 假设表名是 CRMProduct
        fields: ['image', 'cnname', 'parameters', 'note'],
        filters: {
          crmorder_id: this.order_data.id
        },
        kw: '',
        total: 0,
        page: 1,
        pagesize: 1000, // 可以设置一个较大的值来下载更多数据
        order_by: '',
        order_desc: 0
      },
      availableFields: [
        { label: '图片', value: 'image' },
        { label: '中文名称', value: 'cnname' },
        { label: '英文名称', value: 'enname' },
        { label: 'SKU', value: 'sku' },
        { label: '产品类型', value: 'product_type' },
        { label: '数量', value: 'quantity' },
        { label: '型号', value: 'model' },
        { label: '技术参数', value: 'parameters' },
        { label: 'PI交货周期', value: 'pi_lead_period' },
        { label: '厂家供货周期', value: 'manufacture_lead_period' },
        { label: '备注', value: 'note' }
      ],
      showDownload: false,
      generateing: false,
      download_url: '',
      table_name: 'CRMProduct',
      childFormVisible: false,
      listLoading: false,
      editloading: false,
      data: [],
      // 这里定义校验规则
      rules: {
        // 为需要校验的字段添加规则，例如:
        cnname: [{ required: true, message: '请输入产品名称', trigger: 'blur' }]
      },
      action: 'create',
      imageUrl: null,
      temp: this.initTemp(),
      kwInput: '',
      order_by: '',
      order_desc: orderMapper[0],
      // pagination
      pagesize: 20,
      page: 1,
      total: 0,
      products: [],
      timeout: null
    }
  },
  watch: {
    order_data: {
      handler(v) {
        this.downloadTemp.filters.crmorder_id = v.id
        this.getList()
      },
      immediate: true // 立即触发一次 handler
    }
  },
  methods: {
    removeImage(index) {
      this.temp.images.splice(index, 1)
    },
    handleInsertFile(item) {
      if (!this.temp.crmfiles) {
        this.temp.crmfiles = []
      }

      // 检查是否已存在（优先使用ID，否则使用URL）
      const existingIndex = this.temp.crmfiles.findIndex(file =>
        (file.id && item.id && file.id === item.id) ||
        (file.url === item.url)
      )

      if (existingIndex === -1) {
        // 现在后端返回完整的CRMFile对象，直接使用即可
        this.temp.crmfiles.push(item)
        this.$message.success(`已添加文件: ${item.filename}`)
      } else {
        this.$message.warning('文件已存在，未重复添加')
      }
    },
    initTemp() {
      const tempData = {
        crmorder_id: this.order_data.id, // 假设为关联的 CRMOrder 的 id，初始化时可能需要特别处理
        cnname: '',
        enname: '',
        sku: '',
        supplier_note: '',
        crmfiles: [],
        product_type: '主产品', // 默认值为 'main'
        image: '',
        quantity: 1, // 默认数量为1
        model: '',
        images: [],
        parameters: '',
        pi_lead_period: 3, // 默认 PI 交货周期天数
        manufacture_lead_period: 3, // 默认厂家供货周期天数
        note: ''
      }

      return tempData
    },
    handleQueryProducts(query, cb) {
      QueryProduct(qs.stringify({
        kw: query,
        pagesize: 10,
        page: 1
      }))
        .then(response => {
          this.products = response.data.data
          if (this.products && this.products.length > 0) {
            this.products.map(function(product) {
              product.value = product.cnname || product.sku
            })
            cb(this.products)
          }
        }).catch(err => {
          console.log(err)
          this.productlistloading = false
        })
    },
    handleProductSelect(row) {
      // 复制
      console.log(row)
      Object.keys(this.temp).forEach(key => {
        if (row[key] !== undefined && key !== 'crmorder_id') this.temp[key] = row[key]
      })
    },
    querySearchProduct(queryString, cb) {
      clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        this.handleQueryProducts(queryString, cb)
      }, 3000 * Math.random())
    },
    handleEditFromTable(row) {
      this.temp = this.initTemp()
      Object.keys(this.temp).forEach(key => {
        if (row[key] !== undefined) this.temp[key] = row[key]
      })
      this.temp.id = row.id
      this.action = 'edit'
      this.childFormVisible = true
    },
    handleDeleteFromTable(row) {
      this.temp.id = row.id
      this.action = 'delete'
      this.$confirm(`确认要删除产品  ${row.product_name}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.confirm()
      }).catch(() => {
      })
    },
    readFileAsBase64(file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        this.imageUrl = e.target.result
        this.temp.file = this.imageUrl
      }
      reader.readAsDataURL(file)
    },
    handlePaste(event) {
      const items = (event.clipboardData || event.originalEvent.clipboardData).items
      for (const item of items) {
        if (item.type.indexOf('image') === 0) {
          const file = item.getAsFile()
          this.readFileAsBase64(file)
          // this.temp.file = file
          // this.imageUrl = URL.createObjectURL(file);
          // console.log(this.imageUrl)
        }
      }
    },
    handleShowDownload() {
      this.showDownload = true
    },
    downloadFile(item) {
      const link = document.createElement('a')
      link.href = item.url
      link.download = item.filename
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    handleShowEdit() {
      this.temp = this.initTemp()
      this.childFormVisible = true
      this.action = 'create'
    },
    resetTemp() {
      this.temp = {
        crmorder_id: this.order_data.id, // 假设为关联的 CRMOrder 的 id，初始化时可能需要特别处理
        cnname: '',
        enname: '',
        sku: '',
        supplier_note: '',
        crmfiles: [],
        product_type: '主产品', // 默认值为 'main'
        image: '',
        quantity: 1, // 默认数量为1
        model: '',
        images: [],
        parameters: '',
        pi_lead_period: 3, // 默认 PI 交货周期天数
        manufacture_lead_period: 3, // 默认厂家供货周期天数
        note: ''
      }
      this.imageUrl = ''
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        page: this.page,
        crmorder_id: this.order_data.id,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
          this.downloadTemp.total = this.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    confirm() {
      switch (this.action) {
        case 'create':
          this.editloading = true
          this.temp.crmorder_id = this.order_data.id

          Post(this.temp).then((response) => {
            this.childFormVisible = false
            this.editloading = false
            this.$emit('reload')
            this.notify('添加成功')
            this.getList()
          }).catch(err => {
            console.log(err)
            this.editloading = false
          })
          break
        case 'delete':
          Delete(this.temp.id).then((response) => {
            this.childFormVisible = false
            this.$emit('reload')
            this.resetTemp()
            this.notify('删除成功')
            this.getList()
          }).catch(err => {
            console.log(err)
            this.editloading = false
          })
          break
        case 'edit':
          this.editloading = true

          Put(this.temp.id, this.temp).then((response) => {
            this.childFormVisible = false
            this.editloading = false
            this.$emit('reload')
            this.resetTemp()
            this.notify('修改成功')
            this.getList()
          }).catch(err => {
            console.log(err)
            this.editloading = false
          })
          break
      }
    },
    cancel() {
      this.childFormVisible = false
    },
    hide() {
      this.$emit('close', false)
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    notify(message) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: 2000
      })
    },
    /**
     * 根据文件信息获取对应的图标类型
     * @param {Object} file - 文件对象，包含filename和content_type
     * @returns {String} 图标类名
     */
    getFileIcon(file) {
      const filename = (file.filename || '').toLowerCase()
      const contentType = (file.content_type || '').toLowerCase()

      // PDF文件
      if (filename.includes('.pdf') || contentType.includes('pdf')) {
        return 'pdf'
      }
      // Excel文件
      if (filename.includes('.xlsx') || filename.includes('.xls') ||
          contentType.includes('spreadsheet') || contentType.includes('excel')) {
        return 'excel'
      }
      // Word文件
      if (filename.includes('.doc') || filename.includes('.docx') ||
          contentType.includes('word') || contentType.includes('document')) {
        return 'word'
      }
      // 压缩文件
      if (filename.includes('.zip') || filename.includes('.rar') || filename.includes('.7z') ||
          contentType.includes('zip') || contentType.includes('rar') || contentType.includes('compressed')) {
        return 'zip'
      }
      // PPT文件
      if (filename.includes('.ppt') || filename.includes('.pptx') ||
          contentType.includes('presentation') || contentType.includes('powerpoint')) {
        return 'ppt'
      }
      // 文本文件
      if (filename.includes('.txt') || contentType.includes('text/plain')) {
        return 'txt'
      }
      // CSV文件
      if (filename.includes('.csv') || contentType.includes('csv')) {
        return 'csv'
      }
      // 默认文档图标
      return 'document'
    },
    /**
     * 从文件名提取扩展名
     * @param {String} filename - 文件名
     * @returns {String} 大写的文件扩展名（不含点）
     */
    getFileExtension(filename) {
      if (!filename) return ''
      const parts = filename.split('.')
      if (parts.length > 1) {
        return parts[parts.length - 1].toUpperCase()
      }
      return ''
    }
  }
}
</script>

<style scoped>
/* 表单优化样式 */
.el-form {
  padding: 10px;
  background-color: #fafafa;
  border-radius: 6px;
}

/* 文件列表样式 */
.file-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 5px;
}

.file-list-display {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 10px;
  padding: 10px;
  background-color: #f9f9f9;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  min-height: 60px;
}

/* 表格中的文件项 */
.file-item-table {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 60px;
}

/* 图片缩略图样式 */
.file-thumbnail {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  cursor: pointer;
  transition: all 0.3s ease;
}

.file-thumbnail:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  border-color: #409eff;
}

/* 图片加载错误样式 */
.image-error {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  color: #c0c4cc;
  font-size: 24px;
}

/* 文件图标链接 */
.file-icon-link {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-decoration: none;
  cursor: pointer;
  transition: all 0.3s ease;
}

.file-icon-link:hover {
  transform: scale(1.1);
}

.file-icon-link:hover .file-type-icon {
  color: #409eff;
}

/* 文件类型图标 */
.file-type-icon {
  width: 48px;
  height: 48px;
  transition: color 0.3s ease;
}

/* 文件扩展名标签 */
.file-name-small {
  margin-top: 4px;
  font-size: 11px;
  color: #606266;
  font-weight: 500;
  text-align: center;
}

/* 表单中的文件项 */
.file-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 120px;
}

.file-icon {
  height: 80px;
  width: 80px;
}

.file-name {
  margin-top: 5px;
  text-align: center;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 12px;
}

/* 表单项间距优化 */
.el-form-item {
  margin-bottom: 18px;
}

/* 文本域样式优化 */
.el-textarea__inner {
  font-family: inherit;
  resize: vertical;
}

/* 按钮区域样式 */
.el-row[type="flex"] {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e8e8e8;
}
  .paste-area {
    border: 2px dashed #ccc;
    padding: 20px;
    text-align: center;
  }
  .mt-dialog >>> span.el-dialog__title {
    word-break: normal;
    width: auto;
    display: block;
    white-space: pre-wrap;
    word-wrap: break-word;
    overflow: hidden;
  }
    .file-item a {
  cursor: pointer;
  transition: transform 0.2s;
}

.file-item a:hover {
  transform: scale(1.1);
}

.file-icon {
  height: 80px;
  width: 80px;
}
</style>
